<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-04-29
 * Time: 17:46
 */

namespace app\repair\controller;

use app\common\BaseLoginCustomer;
use app\exception\CustomException;
use app\model\AcceptOrder;
use app\model\AuthData;
use app\model\Customer;
use app\model\RepairOrder;
use app\model\RepairPerson;
use app\model\ServiceConfig;
use app\service\OrderService;
use app\tools\MIniprogram;
use app\tools\Wxpay;
use think\Exception;
use think\Request;

class Index extends BaseLoginCustomer
{
    private $orderService;
    function __construct(Request $request = null, OrderService $orderService)
    {
        parent::__construct($request);
        $this->orderService = $orderService;
    }

    function checkStatus($type = 0)
    {
        $customer_id = $this->getParam('u_id');
        $data = RepairPerson::where(['customer_id'=> $customer_id])->field('status, service_type, thaw_time')->find();

        if(!$data || in_array($data['status'],  [1, 2, 4]))
        {
            throw new CustomException("AUTH_FAIL");
        }

        if($data['status'] == 5 and time() <= strtotime($data['thaw_time']))
        {
            $time = strtotime($data['thaw_time']) - time();
            $time = gmdate('H时i分s秒',$time);
            echo json_encode([
                "errno" => 100041,
                "errmsg" => "当前账户被冻结，剩余{$time}自动解冻！",
                "statusCode"=> 200,
                "data" => $data
            ], JSON_UNESCAPED_UNICODE);die();
        }

        if($type)
        {
            if(!in_array($type, explode(',', $data['service_type'])))
            {
                throw new CustomException("TYPE_NOT_FIT");
            }
        }
    }

    function auth()
    {
        $data = [
            'fullname'=> $this->getParam('name', ''),
            'wx_number'=> $this->getParam('wx_number', ''),
            'mobile'=> $this->getParam('mobile', ''),
            'service_type'=> $this->getParam('service_type', 0),
            'address'=> $this->getParam('address', ''),
            'lat'=> $this->getParam('lat', 0),
            'lng'=> $this->getParam('lng', 0),
            'distance'=> $this->getParam('distance', 0),
            'status'=> 2,
            'customer_id'=> $this->getParam('u_id', 0),
            'avatar'=> $this->getParam('avatar', 0),
        ];

        $auth = [
            'idcard'=> $this->getParam('idcard', ''),
            'idcard_face'=> $this->getParam('idcard_face', ''),
            'idcard_back'=> $this->getParam('idcard_back', ''),
            'license'=> $this->getParam('license', ''),
        ];

        if(!$data['fullname'] || !$data['wx_number'] || !$data['mobile'] || !$data['service_type'] || !$data['address'] || !$data['distance'] || !$auth['idcard'] || !$auth['idcard_face'] || !$auth['idcard_back'])
        {
            return fail("DATA_ERROR");
        }

        $smscode = $this->getParam('smsCode', '');
        \app\tools\Sms::checkSms($data['mobile'], $smscode);

        $form = [
            'customer_id'=> $this->getParam('u_id', 0),
            'form_id'=> $this->getParam('form_id', ''),
            'openid'=> $this->getParam('openid', 0),
            'create_time'=> time()
        ];
        db('form_data')->insert($form);
        $data['name'] = mb_substr($data['fullname'], 0, 1);
        $id = RepairPerson::createOrUpdate($data);
        $auth['rp_id'] = $id;
        AuthData::createOrUpdate($auth);

        return success([]);

    }

    function createOrder()
    {

        $data = [
            'details'=> $this->getParam('details', ''),
            'images'=> $this->getParam('images', ''),
            'mobile'=> $this->getParam('mobile', ''),
            'address'=> $this->getParam('address', ''),
            'lat'=> $this->getParam('lat', ''),
            'lng'=> $this->getParam('lng', ''),
            'customer_id'=> $this->getParam('u_id', 0),
            'type'=> $this->getParam('type', 1),
            'is_money'=> $this->getParam('is_money', 0),
            'master_id'=> $this->getParam('master_id', 0)
        ];

        if(!$data['details'] || !$data['images'] || !$data['mobile'] || !$data['address'])
        {
            exit(fail("DATA_ERROR"));
        }

        $smscode = $this->getParam('smsCode', '');
        \app\tools\Sms::checkSms($data['mobile'], $smscode);
        $form = [
            'customer_id'=> $this->getParam('u_id', 0),
            'form_id'=> $this->getParam('form_id', ''),
            'openid'=> $this->getParam('openid', 0),
            'create_time'=> time()
        ];
        db('form_data')->insert($form);
        $data2 = $this->orderService->confirm($data);

        $result = [];
        if($data2['total'] && !$data['is_money']){
            $wxpay = new Wxpay();
            $result = $wxpay->unifieOrder([
                "out_trade_no"=> $data2['serial_no'],
                "total"=> $data2['total'],
                "openid"=> $this->userInfo['openid']
            ], config('host').'/api/wxpay/notify');
        }

        return success($result);

    }

    function orderDetail()
    {
        $id = $this->getParam('id', 0);
        $uid = $this->getParam('u_id', 0);
        $lat = $this->getParam('lat', 0);
        $lng = $this->getParam('lng', 0);

        $data = $this->orderService->orderDetail($id, $uid, $lat, $lng);

        return success($data);
    }

    function acceptOrder()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'o_id'=> $this->getParam('o_id', ''),
        ];
        if(!$data['o_id'])
        {
            throw new CustomException("DATA_ERROR");
        }
        $form = [
            'customer_id'=> $this->getParam('u_id', 0),
            'form_id'=> $this->getParam('form_id', ''),
            'openid'=> $this->getParam('openid', 0),
            'create_time'=> time()
        ];
        db('form_data')->insert($form);

        $info = RepairOrder::where(['id'=> $data['o_id']])->field('type, customer_id')->find();
        if($info['customer_id'] == $form['customer_id'])
        {
            throw new CustomException("NOT_ACCEPT_SELF");
        }
        $this->checkStatus($info['type']);
        $this->orderService->acceptOrder($data);
        return success([]);
    }

    function orderList()
    {
        $data = [
            'o.customer_id'=> $this->getParam('u_id', 0),
        ];
        $status = $this->getParam('status', 0);

        if(!$status)
        {
            $where1 = " (o.status > 10 and o.status < 40 )";
        }elseif($status == 1){
            $where1 = "o.status = 40 and a.uid = 0";
        }else{
            $where1 = "o.status = 40 and a.star > 0";
        }

        $list = RepairOrder::alias('o')
            ->join('accept_order a', 'a.o_id = o.id', 'left')
            ->join('service_config s', 's.id = o.type')
            ->where($data)
            ->where($where1)
            ->field('a.star, a.id as a_id, s.name as service_name, o.id, o.type, o.images, o.address, o.status as o_status, a.status as a_status, a.name, a.mobile, o.add_time , a.add_time as a_add_time')
            ->order('o.id desc')
            ->paginate($this->pageSize);

        return success($list);
    }

    function orderCancel()
    {
        $id = $this->getParam('id', 0);
        if(!$id)
        {
            throw new CustomException("DATA_ERROR");
        }
        $this->orderService->orderCancel($id);
        return success([]);

    }

    function orderEdit()
    {
        $data = [
            'id'=> $this->getParam('id', 0),
            'details'=> $this->getParam('details', ''),
            'images'=> $this->getParam('images', ''),
            'mobile'=> $this->getParam('mobile', ''),
            'address'=> $this->getParam('address', ''),
            'lat'=> $this->getParam('lat', ''),
            'lng'=> $this->getParam('lng', ''),
            'customer_id'=> $this->getParam('u_id', 0)
        ];

        if(!$data['id'] || !$data['details'] || !$data['images'] || !$data['mobile'] || !$data['address'])
        {
            exit(fail("DATA_ERROR"));
        }

        $smscode = $this->getParam('smsCode', '');
        \app\tools\Sms::checkSms($data['mobile'], $smscode);

        $data = $this->orderService->orderEdit($data);
        return success([]);
    }

    function orderHistory()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'lat'=> $this->getParam('lat', 0),
            'lng'=> $this->getParam('lng', 0),
        ];
        $status = $this->getParam('status', 0);
        if($status) $data['status'] = $status;
        $this->checkStatus();
        $data = $this->orderService->orderHistory($data);
        return success($data);

    }

    function orderAvailable()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'lat'=> $this->getParam('lat', 0),
            'lng'=> $this->getParam('lng', 0),
            'type'=> $this->getParam('type', 1)
        ];
        if($data['type'] == 2)
        {
            $info = RepairPerson::where(['customer_id'=> $data['customer_id']])->field('lat, lng')->find();
            $data['lat'] = $info['lat'];
            $data['lng'] = $info['lng'];
        }
        $data = $this->orderService->orderAvailable2($data);
        return success($data);

    }

    function userInfo()
    {
        $u_id = $this->getParam('u_id', 0);
        $list = \db('repair_person')->where(['customer_id'=> $u_id])->field('status, operater, operate_time, reason')->find();
        $list['status'] = $list['status']?:1;
        $list['operater'] = $list['operater']?:'';
        $list['operate_time'] = $list['operate_time']?:'';
        $list['reason'] = $list['reason']?:'';
        return success($list);
    }

    function my()
    {
        $customer_id = $this->getParam('u_id', 0);

        $data = $this->orderService->my($customer_id);
        return success($data);
    }

    function recharge()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'id'=> $this->getParam('id', 0)
        ];
        $res = $this->orderService->recharge($data);

        $wxpay = new Wxpay();
        $result = $wxpay->unifieOrder([
            "out_trade_no"=> $res['serial_no'],
            "total"=> $res['total'],
            "openid"=> $this->userInfo['openid']
        ], "https://cat.legu17.com/api/wxpay/notify2");

        return success($result);
    }

    function serviceEdit()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'type'=> $this->getParam('type')
        ];
        $this->checkStatus();
        $this->orderService->serviceEdit($data);
        return success([]);

    }

    function evaluate()
    {
        $data = [
            'o_id'=> $this->getParam('o_id', 0),
            'star'=> $this->getParam('star', 0),
            'eva'=> $this->getParam('eva', ''),
            'uid'=> $this->getParam('u_id', 0),
        ];

        $this->orderService->evaluate($data);
        return success([]);
    }

    function push()
    {
        $data = [
            'id'=> $this->getParam('id', 0),
            'uid'=> $this->getParam('u_id', 0),
        ];

        try
        {
            db('repair_order')->where(['id'=> $data['id'], 'status'=> 21, 'customer_id'=> $data['uid']])->update(['status'=> 20]);
        }catch (Exception $exception){
            throw new CustomException();
        }

        return success([]);
    }


    function acancel()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'id'=> $this->getParam('id', 0)
        ];

        $info = AcceptOrder::where($data)->field('o_id, status')->find();
        if($info['status'] != 30)
        {
            throw new CustomException("ORDER_NOT_CANCEL");
        }
        AcceptOrder::where(['id'=> $data['id']])->delete();
        RepairOrder::where(['id'=> $info['o_id']])->update(['status'=> 20]);
        $status = RepairPerson::where(['customer_id'=> $data['customer_id']])->value('status');
        if($status != 5)
        {
            RepairPerson::where(['customer_id'=> $data['customer_id']])->update([
                'status'=> 5,
                'thaw_time'=> date('Y-m-d H:i:s', time()+86400)
            ]);
        }
        return success([]);
    }

    function acommit()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'id'=> $this->getParam('id', 0)
        ];

        $info = AcceptOrder::where($data)->field('o_id, status, name')->find();
        if($info['status'] != 30)
        {
            throw new CustomException("ORDER_NOT_COMMIT");
        }
        AcceptOrder::where(['id'=> $data['id']])->update(['status'=> 40, 'add_time'=> date('Y-m-d H:i:s')]);
        RepairOrder::where(['id'=> $info['o_id']])->update(['status'=> 36]);

        $order = db('repair_order')->where(['id'=> $info['o_id']])->field('customer_id, order_no')->find();
        $form = db('form_data')->where(['customer_id'=> $order['customer_id']])->field('form_id, openid, id')->order('create_time desc')->find();
        MIniprogram::sendTemplate([
            'openid'=> $form['openid'],
            'template_id'=> 'R3QC9iZovu1rIr3Yocvzl-K7D5Sd4fsWvYc6be99rgg',
            'page'=> 'pages/repair/openRepair/openRepair',
            'form_id'=> $form['form_id'],
            'data'=> [
                'keyword1'=> ['value'=> $order['order_no']],
                'keyword2'=> ['value'=> date('Y-m-d H:i:s')],
                'keyword3'=> ['value'=> "您的订单已完成！！"],
            ]
        ]);
        db('form_data')->where(['id'=> $form['id']])->delete();

        return success([]);
    }

    function commit()
    {
        $data = [
            'customer_id'=> $this->getParam('u_id', 0),
            'id'=> $this->getParam('id', 0),
        ];

        $info = RepairOrder::where($data)->field('id, status, order_no, type')->find();
        if($info['status'] != 36)
        {
            throw new CustomException("ORDER_NOT_COMMIT");
        }
        RepairOrder::where(['id'=> $info['id']])->update(['status'=> 40]);
        $value = ServiceConfig::where(['id'=> $info['type']])->value('tiger_tee');
        Customer::where(['id'=> $data['customer_id']])->setInc('tiger_tee', $value);
        $form = db('form_data')->where(['customer_id'=> $data['customer_id']])->field('form_id, openid, id')->order('create_time desc')->find();

        MIniprogram::sendTemplate([
            'openid'=> $form['openid'],
            'template_id'=> 'EfBc8RvwVtbhZmtajNXuUbhcizk_ijYioBLkNkhndB8',
            'form_id'=> $form['form_id'],
            'page'=> 'pages/mine/mine',
            'data'=> [
                'keyword1'=> ['value'=> date('Y-m-d H:i:s')],
                'keyword2'=> ['value'=> "恭喜您获得{$value}虎牙"],
            ]
        ]);
        db('form_data')->where(['id'=> $form['id']])->delete();

        $customer_id = db('accept_order')->where(['o_id'=> $info['id']])->value('customer_id');
        $form = db('form_data')->where(['customer_id'=> $customer_id])->field('form_id, openid, id')->order('create_time desc')->find();
        MIniprogram::sendTemplate([
            'openid'=> $form['openid'],
            'template_id'=> 'R3QC9iZovu1rIr3Yocvzl-K7D5Sd4fsWvYc6be99rgg',
            'form_id'=> $form['form_id'],
            'page'=> 'pages/repair/worker/workerCenter/workerCenter',
            'data'=> [
                'keyword1'=> ['value'=> $info['order_no']],
                'keyword2'=> ['value'=> date('Y-m-d H:i:s')],
                'keyword3'=> ['value'=> "您的订单已完成！！"],
            ]
        ]);
        db('form_data')->where(['id'=> $form['id']])->delete();

        return success([]);
    }

    function formDataAdd()
    {
        $form = [
            'customer_id'=> $this->getParam('u_id', 0),
            'form_id'=> $this->getParam('form_id', ''),
            'openid'=> $this->getParam('openid', 0),
            'create_time'=> time()
        ];

        db('form_data')->insert($form);
        return success([]);
    }

    function updateAddress()
    {
        $post = [
            'address'=> $this->getParam('address', ''),
            'lat'=> $this->getParam('lat', 0),
            'lng'=> $this->getParam('lng', 0),
            'customer_id'=> $this->getParam('u_id', 0)
        ];

        if(!$post['address'])
        {
            throw new CustomException("DATA_ERROR");
        }

        RepairPerson::where(['customer_id'=> $post['customer_id']])->update($post);
        return success([]);
    }
}